
package com.insigma.business.qrcode.soldier._provider.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;

import com.insigma.business.qrcode.common.dao.CommonAdminAreaDO;
import com.insigma.business.qrcode.common.dto.*;
import com.insigma.business.qrcode.common.entity.ZzdOrganizationDetailBO;
import com.insigma.business.qrcode.common._provider.CommonAdminAreaProvider;
import com.insigma.business.qrcode.common.service.CommonAdminAreaService;
import com.insigma.business.qrcode.common.service.ZzdService;
import com.insigma.business.qrcode.common.util.AdminAreaCodeUtils;
import com.insigma.business.qrcode.common.util.BizCheckUtil;
import com.insigma.business.qrcode.common.util.ResponseUtils;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.soldier._provider.GovMessageProvider;
import com.insigma.business.qrcode.soldier.dto.GovMessageDTO;
import com.insigma.business.qrcode.soldier.dto.VisitSourceEnum;
import com.insigma.business.qrcode.soldier.dto.gov.BaseProviderImpl;
import com.insigma.business.qrcode.soldier.entity.GovEmployeeDO;
import com.insigma.business.qrcode.soldier.entity.GovOrgDO;
import com.insigma.business.qrcode.soldier.entity.SoldierBasicInfoDO;
import com.insigma.business.qrcode.soldier.request.GovCommonTaskMessageRequest;
import com.insigma.business.qrcode.soldier.request.GovMessageRequest;
import com.insigma.business.qrcode.soldier.service.SoldierBasicInfoService;
import com.insigma.business.qrcode.soldier.service.ZzdGovOrgService;
import com.insigma.business.qrcode.soldier.util.NativeImgUtils;
import com.insigma.business.qrcode.soldier.util.PrivacyDimmer;
import com.insigma.business.qrcode.soldier.util.ThreadPoolManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
@Component("govMessageProvider")
public class GovMessageProviderImpl extends BaseProviderImpl implements GovMessageProvider {

    @Autowired
    private CommonAdminAreaProvider commonAdminAreaProvider;

    @Autowired
    private CommonAdminAreaService commonAdminAreaService;

    @Autowired
    private ZzdService zzdService;

    @Autowired
    private ZzdGovOrgService zzdGovOrgService;

    @Autowired
    private SoldierBasicInfoService soldierBasicInfoService;


    @Autowired
    private ZzdGovOrgService stableZzdGovOrgService;

    @Override
    public BaseResponse<GovMessageDTO> sendFwzMessage(GovMessageRequest request) {
        log.info("下发请求给服务站：{}", request);
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotBlank(request.getIdCardNo(), "身份证不能为空");
        BizCheckUtil.checkNotBlank(request.getTitle(), "标题不能为空");
        BizCheckUtil.checkNotBlank(request.getContent(), "内容不能为空");

        GovMessageDTO result = new GovMessageDTO();

        SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(request.getIdCardNo());
        BizCheckUtil.checkNotNull(byIdCardNo, "查无此人");
        CommonAdminAreaDO commonAdminAreaDO = commonAdminAreaService.get(byIdCardNo.getResidentAdminAreaCode());
        BizCheckUtil.checkNotNull(commonAdminAreaDO, "行政区划错误");
        if (AdminAreaCodeUtils.getCutdAreaCode(byIdCardNo.getResidentAdminAreaCode()).equals("3301")) {

            List<String> users = Lists.newArrayList("-");
            zzdService.sendFwzMessage(users, request.getTitle(), request.getContent(), request.getIdCardNo(), request.getMobile(), request.getRealName(), request.getAddress(), commonAdminAreaDO.getValue().replace("/浙江省/杭州市/", ""));
            result.setUsers(users);
            return ResponseUtils.buildSuccessResponse(result);
        }

        List<GovEmployeeDO> govEmployeeDOS = zzdGovOrgService.listEmployeeByAdminAreaCode(byIdCardNo.getResidentAdminAreaCode());
        if (!CollectionUtils.isEmpty(govEmployeeDOS)) {
            List<String> users = govEmployeeDOS.stream().map(GovEmployeeDO::getOuterGovAccountId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(users)) {
                for (String user : users) {
                    zzdService.sendFwzMessage(Lists.newArrayList(user), request.getTitle(), request.getContent(), request.getIdCardNo(), request.getMobile(), request.getRealName(), request.getAddress(), commonAdminAreaDO.getValue().replace("/浙江省/杭州市/", ""));
                }
            }
            result.setUsers(users);
        }

        return ResponseUtils.buildSuccessResponse(result);
    }

    @Override
    public BaseResponse<String> sendSubFwzMessage(GovMessageRequest request, String managerAreaCode) {
        log.info("下发请求给服务站：{}", request);
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotBlank(request.getIdCardNo(), "身份证不能为空");
        BizCheckUtil.checkNotBlank(request.getTitle(), "标题不能为空");
        BizCheckUtil.checkNotBlank(request.getContent(), "内容不能为空");

        GovMessageDTO result = new GovMessageDTO();
        List<String> userNames = Lists.newArrayList();

        SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(request.getIdCardNo());
        BizCheckUtil.checkNotNull(byIdCardNo, "查无此人");

        CommonAdminAreaDO commonAdminAreaDO = commonAdminAreaService.get(byIdCardNo.getResidentAdminAreaCode());
        BizCheckUtil.checkNotNull(commonAdminAreaDO, "行政区划错误");

        String soldierAreaCode = byIdCardNo.getResidentAdminAreaCode();
        if (AdminAreaCodeUtils.getCutdAreaCode(soldierAreaCode).equals("3301")) {

            List<String> users = Lists.newArrayList("-");
            zzdService.sendFwzMessage(users, request.getTitle(), request.getContent(), request.getIdCardNo(), request.getMobile(), request.getRealName(), request.getAddress(), commonAdminAreaDO.getValue().replace("/浙江省/杭州市/", ""));
            result.setUsers(users);
            userNames.add("-");
            log.info("下发用户：{}", userNames);
            return ResponseUtils.buildSuccessResponse(String.join(",", userNames));
        }
        int level = AdminAreaCodeUtils.getLevel(managerAreaCode);
        int nextCodeLength = AdminAreaCodeUtils.getNextCodeLength(managerAreaCode);
        soldierAreaCode = AdminAreaCodeUtils.fillAreaCode(soldierAreaCode.substring(0, nextCodeLength));

        List<GovEmployeeDO> govEmployeeDOS = zzdGovOrgService.listEmployeeByAdminAreaCode(soldierAreaCode);
        BizCheckUtil.checkIsTrue(!CollectionUtils.isEmpty(govEmployeeDOS), "该地区人员还未配置！");

        List<String> users = govEmployeeDOS.stream()
                .filter(s -> "ENABLED".equals(s.getStatus()))
                .filter(s -> s.getType() != null && s.getType().contains("JOB"))
                .map(GovEmployeeDO::getOuterGovAccountId)
                .collect(Collectors.toList());
        userNames = govEmployeeDOS.stream().filter(s -> "ENABLED".equals(s.getStatus()))
                .filter(s -> s.getType() != null && s.getType().contains("JOB"))
                .map(GovEmployeeDO::getAccountName).collect(Collectors.toList());
        log.info("下发用户：{}", userNames);

        BizCheckUtil.checkIsTrue(!CollectionUtils.isEmpty(users), "该地区人员还未配置！");
        if (!CollectionUtils.isEmpty(users)) {
            List<String> shiId = Lists.newArrayList();
            if (level != 2) {
                int codeLength = AdminAreaCodeUtils.getLevelLength("3");
                String fillAreaCode = AdminAreaCodeUtils.fillAreaCode(soldierAreaCode.substring(0, codeLength));
                List<GovEmployeeDO> job = zzdGovOrgService.getFwzWorkers(fillAreaCode, "JOB");
                shiId = job.stream().map(s -> s.getOuterGovAccountId()).collect(Collectors.toList());
            }
            for (String user : users) {
                if (level == 2) {
                    zzdService.sendFwzMessage(Lists.newArrayList(user), request.getTitle(), request.getContent(), request.getIdCardNo(), request.getMobile(),
                            request.getRealName(), request.getAddress(), commonAdminAreaDO.getValue().replace("/浙江省/杭州市/", ""));
                } else {
                    zzdService.sendFwzMessageOfXz(Lists.newArrayList(user), shiId, request.getTitle(), request.getContent(), request.getIdCardNo(), request.getMobile(),
                            request.getRealName(), request.getAddress(), commonAdminAreaDO.getValue().replace("/浙江省/杭州市/", ""));
                }
            }
        }

        result.setUsers(users);

        return ResponseUtils.buildSuccessResponse(String.join(",", userNames));
    }

    @Override
    public BaseResponse<String> sendStreetFwzMessageOfDifficulty(GovMessageRequest request) {
        log.info("下发请求给服务站：{}", request);
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotBlank(request.getIdCardNo(), "身份证不能为空");
        BizCheckUtil.checkNotBlank(request.getTitle(), "标题不能为空");
        BizCheckUtil.checkNotBlank(request.getContent(), "内容不能为空");

        GovMessageDTO result = new GovMessageDTO();
        List<String> userNames = Lists.newArrayList();

        SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(request.getIdCardNo());
        BizCheckUtil.checkNotNull(byIdCardNo, "查无此人");

        CommonAdminAreaDO commonAdminAreaDO = commonAdminAreaService.get(byIdCardNo.getResidentAdminAreaCode());
        BizCheckUtil.checkNotNull(commonAdminAreaDO, "行政区划错误");

        String soldierAreaCode = byIdCardNo.getResidentAdminAreaCode();
        if (AdminAreaCodeUtils.getCutdAreaCode(soldierAreaCode).equals("3301")) {

            List<String> users = Lists.newArrayList("-");

            zzdService.sendFwzDifficultyMessage(users, request.getUid(), "智慧老兵发起的困难帮扶", NativeImgUtils.convertToYidaObject(request.getImg()), request.getRealName(), request.getIdCardNo(), request.getMobile(), request.getSoldierType(), request.getGenderStr(),
                    request.getBirthday(), commonAdminAreaDO.getValue().replace("/浙江省/杭州市/", ""), request.getAddress(), request.getReason());
            result.setUsers(users);
            userNames.add("-");
            log.info("下发用户：{}", userNames);
            return ResponseUtils.buildSuccessResponse(String.join(",", userNames));
        }
        int codeLength = AdminAreaCodeUtils.getLevelLength("4");
        soldierAreaCode = AdminAreaCodeUtils.fillAreaCode(soldierAreaCode.substring(0, codeLength));

        List<GovEmployeeDO> govEmployeeDOS = zzdGovOrgService.listEmployeeByAdminAreaCode(soldierAreaCode);
        if (!CollectionUtils.isEmpty(govEmployeeDOS)) {
            List<String> users = govEmployeeDOS.stream().filter(s -> "ENABLED".equals(s.getStatus())).map(GovEmployeeDO::getOuterGovAccountId).collect(Collectors.toList());
            userNames = govEmployeeDOS.stream().filter(s -> "ENABLED".equals(s.getStatus())).map(GovEmployeeDO::getAccountName).collect(Collectors.toList());
            log.info("下发用户：{}", userNames);
            zzdService.sendFwzDifficultyMessage(users, request.getUid(), "智慧老兵发起的困难帮扶", NativeImgUtils.convertToYidaObject(request.getImg()), request.getRealName(), request.getIdCardNo(), request.getMobile(), request.getSoldierType(), request.getGenderStr(),
                    request.getBirthday(), commonAdminAreaDO.getValue().replace("/浙江省/杭州市/", ""), request.getAddress(), request.getReason());
            result.setUsers(users);
        }

        return ResponseUtils.buildSuccessResponse(String.join(",", userNames));
    }

    @Override
    public BaseResponse<String> sendStreetFwzMessageOfDifficultyOfCheck(GovMessageRequest request) {
        log.info("下发请求给服务站：{}", request);
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotBlank(request.getIdCardNo(), "身份证不能为空");
        BizCheckUtil.checkNotBlank(request.getTitle(), "标题不能为空");
        BizCheckUtil.checkNotBlank(request.getContent(), "内容不能为空");

        GovMessageDTO result = new GovMessageDTO();
        List<String> userNames = Lists.newArrayList();

        SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(request.getIdCardNo());
        BizCheckUtil.checkNotNull(byIdCardNo, "查无此人");

        CommonAdminAreaDO commonAdminAreaDO = commonAdminAreaService.get(byIdCardNo.getResidentAdminAreaCode());
        BizCheckUtil.checkNotNull(commonAdminAreaDO, "行政区划错误");

        String soldierAreaCode = byIdCardNo.getResidentAdminAreaCode();
        if (AdminAreaCodeUtils.getCutdAreaCode(soldierAreaCode).equals("3301")) {

            List<String> users = Lists.newArrayList("-");

            zzdService.sendFwzDifficultyCheckNotice(users, request.getUid(), NativeImgUtils.convertToYidaObject(request.getImg()), request.getRealName(), request.getIdCardNo(), request.getMobile(), request.getSoldierType(), request.getGenderStr(),
                    request.getBirthday(), commonAdminAreaDO.getValue().replace("/浙江省/杭州市/", ""), request.getAddress(), request.getReason());
            result.setUsers(users);
            userNames.add("-");
            log.info("下发用户：{}", userNames);
            return ResponseUtils.buildSuccessResponse(String.join(",", userNames));
        }
        int codeLength = AdminAreaCodeUtils.getLevelLength("4");
        soldierAreaCode = AdminAreaCodeUtils.fillAreaCode(soldierAreaCode.substring(0, codeLength));

        List<GovEmployeeDO> govEmployeeDOS = zzdGovOrgService.listEmployeeByAdminAreaCode(soldierAreaCode);
        if (!CollectionUtils.isEmpty(govEmployeeDOS)) {
            List<String> users = govEmployeeDOS.stream().filter(s -> "ENABLED".equals(s.getStatus())).map(GovEmployeeDO::getOuterGovAccountId).collect(Collectors.toList());
            userNames = govEmployeeDOS.stream().filter(s -> "ENABLED".equals(s.getStatus())).map(GovEmployeeDO::getAccountName).collect(Collectors.toList());
            log.info("下发用户：{}", userNames);
            zzdService.sendFwzDifficultyCheckNotice(users, request.getUid(), NativeImgUtils.convertToYidaObject(request.getImg()), request.getRealName(), request.getIdCardNo(), request.getMobile(), request.getSoldierType(), request.getGenderStr(),
                    request.getBirthday(), commonAdminAreaDO.getValue().replace("/浙江省/杭州市/", ""), request.getAddress(), request.getReason());
            result.setUsers(users);
        }

        return ResponseUtils.buildSuccessResponse(String.join(",", userNames));
    }

    @Override
    public BaseResponse<String> sendCountyFwzMessageOfDifficulty(GovMessageRequest request, String managerAreaCode) {
        log.info("下发请求给服务站：{}", request);
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotBlank(request.getIdCardNo(), "身份证不能为空");
        BizCheckUtil.checkNotBlank(request.getTitle(), "标题不能为空");
        BizCheckUtil.checkNotBlank(request.getContent(), "内容不能为空");

        GovMessageDTO result = new GovMessageDTO();
        List<String> userNames = Lists.newArrayList();

        SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(request.getIdCardNo());
        BizCheckUtil.checkNotNull(byIdCardNo, "查无此人");

        CommonAdminAreaDO commonAdminAreaDO = commonAdminAreaService.get(byIdCardNo.getResidentAdminAreaCode());
        BizCheckUtil.checkNotNull(commonAdminAreaDO, "行政区划错误");

        String soldierAreaCode = byIdCardNo.getResidentAdminAreaCode();
        if (AdminAreaCodeUtils.getCutdAreaCode(soldierAreaCode).equals("3301")) {

            List<String> users = Lists.newArrayList("-");

            zzdService.sendFwzDifficultyMessage(users, request.getUid(), "智慧老兵发起的困难帮扶", NativeImgUtils.convertToYidaObject(request.getImg()), request.getRealName(), request.getIdCardNo(), request.getMobile(), request.getSoldierType(), request.getGenderStr(),
                    request.getBirthday(), commonAdminAreaDO.getValue().replace("/浙江省/杭州市/", ""), request.getAddress(), request.getReason());
            result.setUsers(users);
            userNames.add("-");
            log.info("下发用户：{}", userNames);
            return ResponseUtils.buildSuccessResponse(String.join(",", userNames));
        }
        int level = AdminAreaCodeUtils.getLevel(managerAreaCode);
        int nextCodeLength = AdminAreaCodeUtils.getNextCodeLength(managerAreaCode);
        soldierAreaCode = AdminAreaCodeUtils.fillAreaCode(soldierAreaCode.substring(0, nextCodeLength));


        List<GovEmployeeDO> govEmployeeDOS = zzdGovOrgService.listEmployeeByAdminAreaCode(soldierAreaCode);
        if (!CollectionUtils.isEmpty(govEmployeeDOS)) {
            List<String> users = govEmployeeDOS.stream().filter(s -> "ENABLED".equals(s.getStatus())).map(GovEmployeeDO::getOuterGovAccountId).collect(Collectors.toList());
            userNames = govEmployeeDOS.stream().filter(s -> "ENABLED".equals(s.getStatus())).map(GovEmployeeDO::getAccountName).collect(Collectors.toList());
            log.info("下发用户：{}", userNames);
            if (level == 2) {
                zzdService.sendFwzDifficultyMessage(users, request.getUid(), "智慧老兵发起的困难帮扶", NativeImgUtils.convertToYidaObject(request.getImg()), request.getRealName(), request.getIdCardNo(), request.getMobile(), request.getSoldierType(), request.getGenderStr(),
                        request.getBirthday(), commonAdminAreaDO.getValue().replace("/浙江省/杭州市/", ""), request.getAddress(), request.getReason());
            } else {
                zzdService.sendFwzDifficultyMessageOfXz(users, request.getUid(), "智慧老兵发起的困难帮扶", NativeImgUtils.convertToYidaObject(request.getImg()), request.getRealName(), request.getIdCardNo(), request.getMobile(), request.getSoldierType(), request.getGenderStr(),
                        request.getBirthday(), commonAdminAreaDO.getValue().replace("/浙江省/杭州市/", ""), request.getAddress(), request.getReason());
            }
            result.setUsers(users);

        }

        return ResponseUtils.buildSuccessResponse(String.join(",", userNames));
    }

    @Override
    public BaseResponse<String> sendCountyFwzMessageOfZyqt(GovMessageRequest request) {
        log.info("下发请求给服务站：{}", request);
        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotBlank(request.getIdCardNo(), "身份证不能为空");
        BizCheckUtil.checkNotBlank(request.getTitle(), "标题不能为空");
        BizCheckUtil.checkNotBlank(request.getContent(), "内容不能为空");
        BizCheckUtil.checkIsTrue(!CollectionUtils.isEmpty(request.getWorkers()), "该地区人员还未配置，请联系管理员！");

        GovMessageDTO result = new GovMessageDTO();

        SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(request.getIdCardNo());
        BizCheckUtil.checkNotNull(byIdCardNo, "查无此人");

        CommonAdminAreaDO commonAdminAreaDO = commonAdminAreaService.get(byIdCardNo.getResidentAdminAreaCode());
        BizCheckUtil.checkNotNull(commonAdminAreaDO, "行政区划错误");


        zzdService.sendHealthVisitMessage(request.getWorkers(), request.getUid(), "智慧老兵发起的困难帮扶", request.getRealName(), PrivacyDimmer.desensitizedIdCardNo(request.getIdCardNo()), request.getMobile(), request.getSoldierType(), request.getGenderStr(),
                request.getBirthday(), commonAdminAreaDO.getValue().replace("/浙江省/杭州市/", ""), request.getAddress(), request.getReason(), request.getDeadline());
        result.setUsers(request.getWorkers());
        log.info("下发用户：{}", request.getWorkers());
        return ResponseUtils.buildSuccessResponse(String.join(",", request.getWorkers()));

    }

    @Override
    public BaseResponse<String> sendCommonFwzSubMessage(GovCommonTaskMessageRequest request, String managerAreaCode) {
        log.info("下发给通用的接口：{}, {}", request, managerAreaCode);
        BizCheckUtil.checkNotNull(request.getIdCardNo());
        BizCheckUtil.checkNotNull(request.getUid());
        BizCheckUtil.checkNotNull(request.getTitle());
        BizCheckUtil.checkNotNull(request.getTaskType());
        BizCheckUtil.checkNotNull(request.getReason());

        SoldierBasicInfoDO soldierBasicInfoDO = soldierBasicInfoService.getByIdCardNo(request.getIdCardNo());
        BizCheckUtil.checkNotNull(soldierBasicInfoDO, "记录不存在！");

        CommonAdminAreaDO commonAdminAreaDO = commonAdminAreaService.get(soldierBasicInfoDO.getResidentAdminAreaCode());
        BizCheckUtil.checkNotNull(commonAdminAreaDO, "行政区划错误");

        if (Strings.isBlank(managerAreaCode)) {
            String cutAdminAreaCode = AdminAreaCodeUtils.getCutAdminAreaCode(soldierBasicInfoDO.getResidentAdminAreaCode(), 3);
            managerAreaCode = AdminAreaCodeUtils.fillAreaCode(cutAdminAreaCode);
        }

        List<String> workers = Lists.newArrayList();

        if (Strings.isBlank(request.getFwzType())) {
            request.setFwzType(VisitSourceEnum.JOB.name());
        }
        List<GovEmployeeDO> employeeDOS = zzdGovOrgService.getRootSubFwzWorkers(managerAreaCode, soldierBasicInfoDO.getResidentAdminAreaCode(), request.getFwzType());
        if (!CollectionUtils.isEmpty(employeeDOS)) {
            workers = employeeDOS.stream().map(GovEmployeeDO::getOuterGovAccountId).collect(Collectors.toList());
            List<String> workerNames = employeeDOS.stream().map(GovEmployeeDO::getRealName).collect(Collectors.toList());
            List<String> ids = employeeDOS.stream().map(GovEmployeeDO::getId).collect(Collectors.toList());

            CommonVisitYidaRequest yidaRequest = new CommonVisitYidaRequest();
            yidaRequest.setUserId(workers);
            yidaRequest.setUid(request.getUid());
            yidaRequest.setTitle(request.getTitle());

            yidaRequest.setRealName(soldierBasicInfoDO.getRealName());
            yidaRequest.setIdCardNo(soldierBasicInfoDO.getIdCardNo());
            yidaRequest.setMobile(soldierBasicInfoDO.getMobile());
            yidaRequest.setSoldierType(soldierBasicInfoDO.getSoldierType());
            yidaRequest.setGenderStr("MALE".equals(soldierBasicInfoDO.getGender()) ? "男" : "女");

            yidaRequest.setBirthday(DateUtil.format(soldierBasicInfoDO.getBirthday(), "yyyy-MM-dd HH:mm:ss"));
            yidaRequest.setAdminAreaValue(commonAdminAreaDO.getFullValuePath().replace("/浙江省/杭州市/", ""));
            yidaRequest.setAddress(soldierBasicInfoDO.getResidentAddress());
            yidaRequest.setReason(request.getReason());
            yidaRequest.setDealRemark(request.getDealRemark());
            yidaRequest.setDeadline(request.getDeadline());
            yidaRequest.setTaskType(request.getTaskType());
            String s = zzdService.sendCommonVisitMessage(yidaRequest);
            return ResponseUtils.buildSuccessResponse(String.join(",", workerNames));
        }
        return ResponseUtils.buildSuccessResponse("");
    }

    @Override
    public BaseResponse<String> sendNotice(String receiverIds, String msg) {
        String s = zzdService.sendNotice(receiverIds, msg);
        return ResponseUtils.buildSuccessResponse(s);
    }

    @Override
    public BaseResponse<String> sendNoticeOfNews(String receiverIds, String msg) {
        String s = zzdService.sendNoticeOfNews(receiverIds, msg);
        return ResponseUtils.buildSuccessResponse(s);
    }

    @Transactional
    @Override
    public BaseResponse refreshAllZzdGovInfo(String adminAreaCode) {
        ThreadPoolManager.getInstance().submit(new Runnable() {
            @Override
            public void run() {
                try {
                    String myCode = "330100000000";
                    if (Strings.isNotBlank(adminAreaCode)) {
                        myCode = adminAreaCode;
                    }
                    ZzdOrganizationDetailBO zzdTree = zzdService.recursionGetOrgAndEmp("GO_39eeb02b368b4680a75bb9291d8901bb");
                    Map<String, ZzdOrganizationDetailBO> allGovMap = new HashMap<>();
                    buildMap(zzdTree, allGovMap);
                    zzdGovOrgService.realDelAllOriginData(myCode);
                    saveNodeGovAndEmp(zzdTree, null, allGovMap, myCode);
                } catch (Exception e) {
                    log.error("error:{}", e);
                }
            }
        });


        return ResponseUtils.buildSuccessResponse("");
    }

    @Override
    public BaseResponse refreshAllZzdGovInfoOfYida(String adminAreaCode) {
        ThreadPoolManager.getInstance().submit(new Runnable() {
            @Override
            public void run() {
                try {
                    String myCode = "330100000000";
                    if (Strings.isNotBlank(adminAreaCode)) {
                        myCode = adminAreaCode;
                    }


                    List<ZzdOrganizationDetailBO> govList = new ArrayList<>();
                    int pageNo = 1;
                    List<YiDaDataBO> data = new ArrayList<>();
                    do {
                        for (YiDaDataBO datum : data) {
                            JSONObject formData = datum.getFormData();
                            govList.addAll(buildYidaLastFwz(formData));
                        }

                        YiDaResponse yiDaResponse = zzdService.yidaFwzList(pageNo++, 50);
                        data = yiDaResponse.getResult().getData();

                    } while (!CollectionUtils.isEmpty(data));
                    Collections.sort(govList, new Comparator<ZzdOrganizationDetailBO>() {
                        @Override
                        public int compare(ZzdOrganizationDetailBO o1, ZzdOrganizationDetailBO o2) {
                            return o1.getOrganizationCode().compareTo(o2.getOrganizationCode());
                        }
                    });
                    Map<String, ZzdOrganizationDetailBO> allGovMap = new LinkedHashMap<>();
                    for (ZzdOrganizationDetailBO zzdOrganizationDetailBO : govList) {
                        allGovMap.put(zzdOrganizationDetailBO.getOrganizationCode(), zzdOrganizationDetailBO);
                    }

                    for (ZzdOrganizationDetailBO value : allGovMap.values()) {
                        String parentCode = value.getParentCode();
                        if (Strings.isNotBlank(parentCode)) {
                            ZzdOrganizationDetailBO zzdOrganizationDetailBO = allGovMap.get(parentCode);
                            zzdOrganizationDetailBO.getSubOrg().add(value);
                        }
                    }


                    List<ZzdEmployeeDetailBO> employees = new ArrayList<>();
                    pageNo = 1;
                    List<YiDaDataBO> data2 = new ArrayList<>();
                    do {
                        for (YiDaDataBO datum : data2) {
                            JSONObject formData = datum.getFormData();
                            employees.add(buildYidaPerson(formData, datum.getOriginator().getName().getZh_CN(), datum.getOriginator().getUserId()));
                        }

                        YiDaResponse yiDaResponse = zzdService.yidaWorkerList(pageNo++, 50);
                        data2 = yiDaResponse.getResult().getData();

                    } while (!CollectionUtils.isEmpty(data2));


                    for (ZzdEmployeeDetailBO employee : employees) {
                        String govCode = employee.getGovCode();
                        ZzdOrganizationDetailBO zzdOrganizationDetailBO = allGovMap.get(govCode);
                        if (zzdOrganizationDetailBO != null) {
                            Boolean nameSame = isNameSame(zzdOrganizationDetailBO.getEmployees(), employee);
                            if (!nameSame) {
                                zzdOrganizationDetailBO.getEmployees().add(employee);
                            }
                        } else {
                            System.out.println();
                        }
                    }
                    ZzdOrganizationDetailBO zzdTree = allGovMap.get("330100");


                    System.out.println();
                    zzdGovOrgService.realDelAllOriginData(myCode);
                    saveNodeGovAndEmp(zzdTree, null, allGovMap, myCode);
                } catch (Exception e) {
                    log.error("error:{}", e);
                }
            }
        });


        return ResponseUtils.buildSuccessResponse("");
    }

    private Boolean isNameSame(List<ZzdEmployeeDetailBO> employees, ZzdEmployeeDetailBO employee) {
        for (ZzdEmployeeDetailBO zzdEmployeeDetailBO : employees) {
            if (employee.getEmployeeName().equals(zzdEmployeeDetailBO.getEmployeeName())) {
                return true;
            }
        }
        return false;
    }

    private ZzdEmployeeDetailBO buildYidaPerson(JSONObject formData, String name, String accountId) {
        String sjCode = formData.getString("textField_kjxuy982");
        String qjCode = formData.getString("textField_kjxuy983");
        String zjCode = formData.getString("textField_kjxuy984");
        String csCode = formData.getString("textField_kjxuy985");
        String mobile = formData.getString("numberField_k7x23sw9_value");
        String quanzhi = formData.getString("radioField_k7wqs75w_id");


        if (Strings.isNotBlank(csCode)) {
            return new ZzdEmployeeDetailBO(name, accountId, csCode, mobile, quanzhi);
        }
        if (Strings.isNotBlank(zjCode)) {
            return new ZzdEmployeeDetailBO(name, accountId, zjCode, mobile, quanzhi);
        }
        if (Strings.isNotBlank(qjCode)) {
            return new ZzdEmployeeDetailBO(name, accountId, qjCode, mobile, quanzhi);
        }
        if (Strings.isNotBlank(sjCode)) {
            return new ZzdEmployeeDetailBO(name, accountId, sjCode, mobile, quanzhi);
        }
        return null;
    }

    private List<ZzdOrganizationDetailBO> buildYidaLastFwz(JSONObject formData) {
        String sjCode = formData.getString("textField_kjxuy982");
        String qjCode = formData.getString("textField_kjxuy983");
        String zjCode = formData.getString("textField_kjxuy984");
        String csCode = formData.getString("textField_kjxuy985");

        String sjValue = formData.getString("textField_kbrb7ahj");
        String qjValue = formData.getString("textField_kbrb7ahk");
        String zjValue = formData.getString("textField_kbrb7ahl");
        String csValue = formData.getString("textField_kbrb7ahm");

        List<ZzdOrganizationDetailBO> result = new ArrayList<>();
        if (Strings.isNotBlank(csCode)) {
            result.add(new ZzdOrganizationDetailBO(csCode, zjCode, csValue));
        }
        if (Strings.isNotBlank(zjCode)) {
            result.add(new ZzdOrganizationDetailBO(zjCode, qjCode, zjValue));
        }
        if (Strings.isNotBlank(qjCode)) {
            result.add(new ZzdOrganizationDetailBO(qjCode, sjCode, qjValue));
        }
        if (Strings.isNotBlank(sjCode)) {
            result.add(new ZzdOrganizationDetailBO(sjCode, null, sjValue));
        }
        return result;
    }

    private void saveNodeGovAndEmp(ZzdOrganizationDetailBO zzdTree, String parentId, Map<String, ZzdOrganizationDetailBO> allGovMap, String excludeCode) {
        if (zzdTree == null) {
            return;
        }


        GovOrgDO govOrgDO = new GovOrgDO();
        govOrgDO.setType("TYJ");
        govOrgDO.setVersion(1);
        govOrgDO.setParentOrgId(parentId);

        govOrgDO.setOuterGovOrgParentId(zzdTree.getParentCode());
        govOrgDO.setOuterGovOrgId(zzdTree.getOrganizationCode());
        govOrgDO.setOuterGovOrgType(zzdTree.getTypeCode());
        govOrgDO.setSequence(zzdTree.getDisplayOrder());
        govOrgDO.setName(zzdTree.getOrganizationName());
        govOrgDO.setAddress(zzdTree.getAddress());
        govOrgDO.setContactNum(zzdTree.getContactNumber());

        String fullPath = getFullPath(zzdTree, allGovMap);
        log.info(fullPath);
        fullPath = fullPath.replace("下城", "拱墅");
        fullPath = fullPath.replace("江干", "上城");
        String code = commonAdminAreaProvider.analyseAreaCodeByBasicInfo(fullPath);

        boolean b = AdminAreaCodeUtils.checkIsFatherArea(excludeCode, code);
        if (b) {
            return;
        }

        govOrgDO.setLeafAdminAreaId(code);
        govOrgDO.setSelfMaintain(false);
        CommonAdminAreaDO commonAdminAreaDO = commonAdminAreaService.get(code);
        if (commonAdminAreaDO != null) {

            govOrgDO.setLeafAdminAreaValue(commonAdminAreaDO.getValue());
        }
        govOrgDO.setStatus(zzdTree.getStatus().equals("A") ? "ENABLED" : "DISABLED");
        zzdGovOrgService.insert(govOrgDO);

        for (ZzdEmployeeDetailBO employee : zzdTree.getEmployees()) {
            GovEmployeeDO employeeDO = new GovEmployeeDO();
            employeeDO.setOuterGovNickName(employee.getEmployeeCode());
            employeeDO.setOuterGovAccountId(employee.getAccountId());
            employeeDO.setOuterGovAccountName(employee.getEmployeeName());
            employeeDO.setAccountName(employee.getEmployeeName());
            employeeDO.setRealName(employee.getEmployeeName());

            employeeDO.setGender(employee.getEmpGender().equals("1") ? "MALE" : "FEMALE");
            employeeDO.setStatus(employee.getStatus().equals("A") ? "ENABLED" : "DISABLED");
            employeeDO.setSelfMaintain(false);

            zzdGovOrgService.insertEmployee(employeeDO);

            for (ZzdPositionDetailBO position : employee.getPositions()) {
                GovEmployeeJobDO jobDO = new GovEmployeeJobDO();
                jobDO.setLeafOrgId(govOrgDO.getId());
                jobDO.setLeafInstituteId(govOrgDO.getId());
                jobDO.setEmployeeId(employeeDO.getId());
                jobDO.setOuterGovLeafOrgId(position.getOrganizationCode());
                jobDO.setOuterGovLeafInstituteId(position.getOrganizationCode());
                jobDO.setJobType(position.isMainJob() ? "MAIN" : "PART");
                jobDO.setJobRole(position.getEmpPosEmployeeRoleCode());
                jobDO.setJobContactNo(position.getGovEmpPosPhoneNo());
                jobDO.setJobPosition(position.getGovEmpPosJob());
                jobDO.setSeqNo(position.getOrderInOrganization());
                jobDO.setStatus(position.getStatus().equals("A") ? "ENABLED" : "DISABLED");
                jobDO.setSelfMaintain(false);
                zzdGovOrgService.insertJob(jobDO);
            }
        }

        for (ZzdOrganizationDetailBO zzdOrganizationDetailBO : zzdTree.getSubOrg()) {
            saveNodeGovAndEmp(zzdOrganizationDetailBO, govOrgDO.getId(), allGovMap, excludeCode);
        }
    }

    private String getFullPath(ZzdOrganizationDetailBO zzdTree, Map<String, ZzdOrganizationDetailBO> allGovMap) {
        String organizationName = zzdTree.getOrganizationName();
        String parentCode = zzdTree.getParentCode();
        if (Strings.isNotBlank(parentCode)) {
            ZzdOrganizationDetailBO zzdOrganizationDetailBO = allGovMap.get(parentCode);
            if (zzdOrganizationDetailBO != null) {
                return getFullPath(zzdOrganizationDetailBO, allGovMap) + organizationName;
            }
        }
        return organizationName;
    }

    private Map<String, ZzdOrganizationDetailBO> buildMap(ZzdOrganizationDetailBO zzdTree, Map map) {
        map.put(zzdTree.getOrganizationCode(), zzdTree);
        for (ZzdOrganizationDetailBO zzdOrganizationDetailBO : zzdTree.getSubOrg()) {
            buildMap(zzdOrganizationDetailBO, map);
        }

        return map;
    }

    private GovEmployeeDO getExistedEmploy(ZzdEmployeeDetailBO employee, List<GovEmployeeDO> allEmployee) {
        List<GovEmployeeDO> collect = Lists.newArrayList();
        for (GovEmployeeDO employeeDO : allEmployee) {
            if (employeeDO.getRealName().equals(employee.getEmployeeName())) {
                collect.add(employeeDO);
            }
        }
        if (!CollectionUtils.isEmpty(collect)) {
            if (collect.size() == 1) {
                return collect.get(0);
            }
        }
        return null;
    }


}
